from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from rest_framework import mixins, viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from rest_framework.views import APIView, Response, status

from utils.common import Pagination
from .models import Faculty
from .serializers import FacultySerializer



class FacultyViewSet(mixins.ListModelMixin,
                     viewsets.GenericViewSet):
    queryset = Faculty.objects.all()
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    # permission_classes = [IsAuthenticated]
    serializer_class = FacultySerializer
    pagination_class = Pagination
    ordering_fields = ('id', )

    @action(methods=['get'], detail=False, url_path='second_faculty')
    def get_second_faculty(self, request, pk=None):
        """ 获取用户有权限查看的二级单位 """

        # 获取所有二级单位
        # first_faculty_codes = Faculty.objects.filter(parent_code__isnull=True)\
        #     .values_list('faculty_code', flat=True)
        # second_faculty_data = Faculty.objects\
        #     .filter(parent_code__in=first_faculty_codes)\
        #     .values('id', 'faculty_code', 'faculty_title')
        #
        second_faculty_data = Faculty.objects.all()\
            .values('id', 'faculty_code', 'faculty_title')

        res_data = second_faculty_data
        return Response({'data': res_data})
